package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constat.MessageConstant;
import com.itheima.constat.RedisConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @authou: fu
 * @date:Created in 2019/12/8
 * @description:
 * @version:1.0
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;


    @RequestMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map map){
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");

        Jedis jedis = jedisPool.getResource();
        //获取redis中的验证码
        String codeInRedis = jedis.get(telephone + RedisConstant.SENDTYPE_LOGIN);

        //校验验证码
        if (codeInRedis == null || validateCode == null || !validateCode.equals(codeInRedis)){
            //校验不通过.返回false
            return  new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        //查询数据库是否是已注册会员,如果不是,自动注册
        Member member =  memberService.findByTelephone(telephone);
        if (member == null){
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberService.add(member);
        }

        //将手机号存到cookie中,为了跟踪用户
        Cookie cookie = new Cookie("login_member_telephone",telephone);
        cookie.setPath("/");
        cookie.setMaxAge(60*60*24*30);
        response.addCookie(cookie);


        //将用户信息保存到redis(模拟session)
        //转换格式
        String memberJson = JSON.toJSON(member).toString();
        jedis.setex(telephone,60*30,memberJson);


        jedis.close();
        return new Result(true,MessageConstant.LOGIN_SUCCESS);
    }
}
